// newDemo
// Created by Administrator on 2025/6/27.
//

#include <iostream>
using namespace std;


class MyClass {
public:
    int age;

    MyClass() : age(0) { ; }
};

void newFunc() {
    MyClass *p = new MyClass();
    p->age = 20;
    cout << "我年龄是：" << p->age << endl;
    delete p;
}

void arrayFunc() {
    int *p = new int[10];
    for (int i = 0; i < 10; i++) {
        p[i] = i;
    }
    cout << "p values:\t";
    for (int i = 0; i < 10; i++) {
        cout << p[i] << "\t";
    }
    cout << endl;
    delete []p;
}

/**
 * nothrow ： 避免分配内存时，发生异常
 */
void nothrowFunc() {
    int *arrPtr = new(nothrow) int[99999999999];
    if (!arrPtr) {
        cerr << "为数组分配内存出现异常" << endl;
    } else {
        cout << "分配成功" << endl;
        delete []arrPtr;
    }
}

/**
 * 分配内存-异常处理
 */
void errorHandleFunc() {
    try {
        const int *arrPtr = new int[99999999999];
        cout << "分配内存成功" << endl;
        delete []arrPtr;
    } catch (const bad_alloc &e) {
        cerr << "分配内存出现异常：" << e.what() << endl;
    }
}


int main(int argc, char *argv[]) {
    // newFunc();
    // arrayFunc();
    // nothrowFunc();
    errorHandleFunc();
    return 0;
}
